package com.techchat.backend.controller;

import com.techchat.backend.model.LoginRequest;
import com.techchat.backend.model.SafeUser;
import com.techchat.backend.model.User;
import com.techchat.backend.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID; // <-- 新增导入
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;
    private final SimpMessagingTemplate messagingTemplate;
    private final String uploadDir = System.getProperty("user.dir") + "/uploads/";
    private final String chatImageUploadDir = System.getProperty("user.dir") + "/chat-uploads/"; // <-- 新增聊天图片上传目录路径

    public UserController(UserService userService, SimpMessagingTemplate messagingTemplate) {
        this.userService = userService;
        this.messagingTemplate = messagingTemplate;

        File avatarDir = new File(uploadDir);
        if (!avatarDir.exists()) {
            avatarDir.mkdirs();
        }

        File chatImgDir = new File(chatImageUploadDir); // <-- 创建聊天图片上传目录
        if (!chatImgDir.exists()) {
            chatImgDir.mkdirs();
        }
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody @Nonnull User user) {
        userService.register(user);
        broadcastAllUsers();
        return ResponseEntity.ok("User registered successfully");
    }

    @PostMapping("/login")
    public ResponseEntity<SafeUser> login(@RequestBody @Nonnull LoginRequest loginRequest) {
        User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
        if (user != null) {
            return ResponseEntity.ok(SafeUser.fromUser(user));
        }
        return ResponseEntity.status(401).build();
    }

    @GetMapping("/all")
    public List<String> getAllUsersNicknames() {
        return userService.getAllNicknames();
    }

    @GetMapping("/allFull")
    public List<SafeUser> getAllUsersFull() {
        return userService.getAllUsers()
                .stream()
                .map(SafeUser::fromUser)
                .collect(Collectors.toList());
    }

    @PutMapping("/nickname")
    public ResponseEntity<String> updateNickname(@RequestBody @Nonnull Map<String, String> payload) {
        String username = payload.get("username");
        String newNickname = payload.get("newNickname");
        if (username == null || newNickname == null) {
            return ResponseEntity.badRequest().body("Missing username or newNickname");
        }
        userService.updateNickname(username, newNickname);
        broadcastAllUsers();
        return ResponseEntity.ok("Nickname updated successfully");
    }

    @PostMapping("/avatar")
    public ResponseEntity<Map<String, Object>> uploadAvatar(
            @RequestParam("username") String username,
            @RequestParam("file") MultipartFile file) {

        if (file.isEmpty() || username == null) {
            return ResponseEntity.badRequest().body(Map.of("error", "Missing file or username"));
        }

        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String ext = "";
        int idx = originalFilename.lastIndexOf('.');
        if (idx > 0) {
            ext = originalFilename.substring(idx);
        }
        String filename = username + "_" + System.currentTimeMillis() + ext;
        File dest = new File(uploadDir + filename);

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "File upload failed"));
        }

        String avatarUrl = "/avatars/" + filename;
        userService.updateAvatar(username, avatarUrl);
        broadcastAllUsers();

        Map<String, Object> response = new HashMap<>();
        response.put("avatar", avatarUrl); // Ensure this key is 'avatar' as per frontend's expectation for general avatar updates.
        // Or more generally `path` or `url`. For broadcastAllUsers, it's likely sufficient.
        return ResponseEntity.ok(response);
    }

    // -------- 新增: 聊天图片上传端点 --------
    @PostMapping("/chat-image/upload")
    public ResponseEntity<Map<String, String>> uploadChatImage(
            @RequestParam("file") MultipartFile file) { // username参数在这里可能不是必需的，除非用于命名或特定逻辑

        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "File is empty"));
        }

        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String ext = "";
        int idx = originalFilename.lastIndexOf('.');
        if (idx > 0) {
            ext = originalFilename.substring(idx);
        }
        // 为聊天图片生成一个独特的文件名
        String filename = "chatimg_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8) + ext;
        File dest = new File(chatImageUploadDir + filename);

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            // 在生产环境中，应该记录更详细的错误或使用自定义异常
            return ResponseEntity.status(500).body(Map.of("error", "Chat image upload failed"));
        }

        String imageUrl = "/chat-images/" + filename; // 客户端将使用的相对URL
        return ResponseEntity.ok(Map.of("imageUrl", imageUrl)); // 返回图片的URL
    }


    // -------- 私有：广播所有用户完整信息 --------
    private void broadcastAllUsers() {
        List<SafeUser> safeUsers = userService.getAllUsers()
                .stream()
                .map(SafeUser::fromUser)
                .collect(Collectors.toList());
        messagingTemplate.convertAndSend("/topic/allUsers", safeUsers);
    }
}
